<template>
  <div class="home-container">
    <!-- 日期选择器 -->
    <div class="date-picker">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange"
      />
    </div>

    <!-- 销售额折线图 -->
    <div class="chart-container">
      <div class="chart-item">
        <h3>销售额趋势</h3>
        <div ref="salesChart" class="chart"></div>
      </div>
    </div>

    <!-- 库存饼图和销量TOP10 -->
    <div class="chart-row">
      <div class="chart-item">
        <h3>库存分布（按品牌）</h3>
        <div ref="inventoryChart" class="chart"></div>
      </div>
      <div class="chart-item">
        <h3>商品销量TOP10</h3>
        <div ref="topSalesChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElDatePicker } from 'element-plus'
import { getSalesTrend, getInventoryDistribution, getTopSales } from '@/api/home'
import { ElMessage } from 'element-plus'

// 图表实例
let salesChartInstance = null
let inventoryChartInstance = null
let topSalesChartInstance = null

// 日期范围
const dateRange = ref([])

// 图表DOM引用
const salesChart = ref(null)
const inventoryChart = ref(null)
const topSalesChart = ref(null)

// 数据
const chartData = ref({
  sales: {
    dates: [],
    values: []
  },
  inventory: [],
  topSales: []
})

// 加载销售额趋势数据
const loadSalesData = async () => {
  try {
    const params = {}
    if (dateRange.value && dateRange.value.length === 2) {
      // 格式化日期为 YYYY-MM-DD 格式
      params.startDate = dateRange.value[0].toISOString().split('T')[0]
      params.endDate = dateRange.value[1].toISOString().split('T')[0]
    }
    const data = await getSalesTrend(params)
    chartData.value.sales = data
    initSalesChart()
  } catch (error) {
    ElMessage.error('获取销售额数据失败')
    console.error('获取销售额数据失败:', error)
  }
}

// 加载库存分布数据
const loadInventoryData = async () => {
  try {
    const data = await getInventoryDistribution()
    chartData.value.inventory = data
    initInventoryChart()
  } catch (error) {
    ElMessage.error('获取库存分布数据失败')
    console.error('获取库存分布数据失败:', error)
  }
}

// 加载销量TOP10数据
const loadTopSalesData = async () => {
  try {
    const data = await getTopSales()
    chartData.value.topSales = data
    initTopSalesChart()
  } catch (error) {
    ElMessage.error('获取销量TOP10数据失败')
    console.error('获取销量TOP10数据失败:', error)
  }
}

// 初始化销售额折线图
const initSalesChart = () => {
  if (!salesChart.value) return
  salesChartInstance = echarts.init(salesChart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: chartData.value.sales.dates
    },
    yAxis: {
      type: 'value',
      name: '销售额（元）'
    },
    series: [{
      data: chartData.value.sales.values,
      type: 'line',
      smooth: true,
      areaStyle: {}
    }]
  }
  salesChartInstance.setOption(option)
}

// 初始化库存饼图
const initInventoryChart = () => {
  if (!inventoryChart.value) return
  inventoryChartInstance = echarts.init(inventoryChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: chartData.value.inventory,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  inventoryChartInstance.setOption(option)
}

// 初始化销量TOP10柱状图
const initTopSalesChart = () => {
  if (!topSalesChart.value) return
  topSalesChartInstance = echarts.init(topSalesChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value',
      name: '销量'
    },
    yAxis: {
      type: 'category',
      data: chartData.value.topSales.map(item => item.name)
    },
    series: [{
      type: 'bar',
      data: chartData.value.topSales.map(item => item.value)
    }]
  }
  topSalesChartInstance.setOption(option)
}

// 处理日期变化
const handleDateChange = () => {
  loadSalesData()
}

// 监听窗口大小变化
const handleResize = () => {
  salesChartInstance?.resize()
  inventoryChartInstance?.resize()
  topSalesChartInstance?.resize()
}

// 加载所有数据
const loadAllData = async () => {
  await Promise.all([
    loadSalesData(),
    loadInventoryData(),
    loadTopSalesData()
  ])
}

onMounted(() => {
  loadAllData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  salesChartInstance?.dispose()
  inventoryChartInstance?.dispose()
  topSalesChartInstance?.dispose()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.date-picker {
  margin-bottom: 20px;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-row {
  display: flex;
  gap: 20px;
}

.chart-item {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart {
  height: 400px;
}

h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
}
</style>